<template>
	<view class="flex-1 flex-col justify-between pb-2">
		<view class="mx-5 px-2 flex-1 flex-col pb-5">
			<view class="rounded-lg p-1 flex-h-center" style="background-color:#97B9D0;">
				<text class="font color-white mb-1">{{warn.label}}</text>
				<text class="font-sm color-white">{{warn.content}}</text>
			</view>
			<view class="flex-1">
				<scroll-view scroll-y="true" class="flex-1 py-1" :scroll-into-view="scrollIntoViewId" @scroll="onScroll"
					lower-threshold="0">
					<view>
						<view class="rounded-lg mb-1 flex flex-wrap" v-for="e,i in msgList" :key="i"
							style="background-color:#97B9D0;padding: 8rpx 16rpx;">
							<ChatBoxVue style="transform: scale(0.8);" @scrollToBottom="scrollToBottom"
								@look-Img="lookImg" :msgInfo="e" :tim="tim" :val="e.payload">
							</ChatBoxVue>
							<!-- <view class="flex" v-if="e.type=='img'">
								<text class="color-white font-sm mr-1">{{e.name}}:</text>
								<uv-image :src="e.text" width="100px" height="100px" mode="aspectFit"
									@click="lookImg(e.text)">
								</uv-image>
							</view>
							<view class="flex" v-else-if="e.type=='astrolabe'" @click="onAstrolabe(e.ids)">
								<text class="color-white font-sm mr-1" style="color:#1BADFF">{{e.name}}:</text>
								<text class="color-white font-sm mr-1" style="color:#1BADFF">{{e.text}}</text>
							</view>
							<text v-else class="font-sm"
								:style="{color:e.type=='tips'?'#1BADFF':'#fff'}">{{e.text}}</text> -->
						</view>
					</view>
					<view id="lastItem"></view>
				</scroll-view>
			</view>
		</view>
		<view class="position-fixed" style="margin-bottom: 20px;padding: 0px 60rpx;width: 750rpx;"
			:style="{bottom:keyHeight}" v-if="inputShow">
			<view
				style="display: flex;flex-direction: row;background-color:#97B9D0;border-radius: 999rpx;overflow: hidden;">
				<uni-easyinput type="text" v-model="msg" placeholder="说点什么" :adjust-position="false"
					@keyboardheightchange="keyboardheightchange" confirmType="send" @confirm="sendMsg" />
				<!-- <button size="mini" style="width:80rpx;margin-left:10px;" @click="sendMsg()">发送</button> -->
			</view>
		</view>
	</view>
</template>

<script setup>
	import TencentCloudChat from '@tencentcloud/chat';
	import ChatBoxVue from '@/pages/msg/components/ChatBox.vue';
	// import {
	// 	tim
	// } from "@/apis/IM.js"
	import dayjs from "dayjs"
	import {
		nextTick,
		ref
	} from 'vue';
	const params = ref(null)

	const msg = ref("")
	const keyHeight = ref('20px')
	const msgList = ref([])
	const scrollIntoViewId = ref('')
	const scrollType = ref(true)
	const room = ref({})
	const {
		inputShow
	} = defineProps(['inputShow'])
	const warn = {
		label: "保密连麦中",
		content: '保密连麦中保密连麦中保密连麦中保密连麦中保密连麦中保密连麦中保密连麦中保密连麦中保密连麦中'
	}
	let tim = null
	// 初始化&登录
	const startChat = (val, options) => {
		params.value = options
		room.value = val
		tim = getApp().globalData.tim
		// chat = TencentCloudChat.create({
		// 	SDKAppID: options.sdkAppId
		// });
		// chat.setLogLevel(1)
		// chat.registerPlugin({
		// 	'tim-upload-plugin': TIMUploadPlugin
		// });

		// chat.login({
		// 	userID: options.userId,
		// 	userSig: options.userSig,
		// }).then(res => {
		// 	console.log('登陆成功');
		// 	chat.on(TencentCloudChat.EVENT.SDK_READY, chatOn);
		// })
		chatOn()
	}
	// 滚动至聊天底部
	const scrollToBottom = () => {
		if (scrollType.value) {
			scrollIntoViewId.value = 'lastItem'
			nextTick(() => {
				scrollIntoViewId.value = ""
			})
		}
	}
	const chatOn = (event) => {
		console.log('初始化成功，开始监听', event);
		createGroup()
		tim.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, getMsg);
	}
	const keyboardheightchange = (e) => {
		keyHeight.value = `${e.detail.height}px`
	}
	// 创建聊天室
	const createGroup = () => {
		tim.createGroup({
			type: TencentCloudChat.TYPES.GRP_AVCHATROOM,
			name: room.value.name,
			groupID: room.value.id
		}).then(res => {
			joinGroup()
		}).catch(err => {
			joinGroup()
		})
	}
	// 加入聊天室
	const joinGroup = () => {
		console.log('直播间Id', room.value.id);
		tim.joinGroup({
				groupID: room.value.id
			})
			.then(() => {
				console.log('加入聊天室')
				// sendMsg(`${uni.getStorageSync('user').nickname}进入直播间`)
				createCustomMessage({
					data: 'tips',
					description: `${uni.getStorageSync('user').nickname}进入直播间`,
					extension: ``
				})
			})
			.catch(err => console.error('加入聊天室失败:', err));
	}
	const emit = defineEmits(['custom', 'lookImg'])
	// 查看图片
	const lookImg = (url) => {
		emit('lookImg', url)
	}
	// 跳转星盘
	const onAstrolabe = (ids) => {
		console.log(ids);
		const idsArr = ids.split(',')
		uni.navigateTo({
			url: `/pages/test/astrolabe?tab=${idsArr.length>1?0:4}&ids=${ids}`
		})
	}
	const addChatList = (obj) => {
		console.log(obj);
		msgList.value.push(obj)
	}
	// 接受消息
	const getMsg = (e) => {
		console.log('接受消息', e);
		e.data.forEach(a => {
			if (a.type == "TIMTextElem") {
				a.payload.data = 'text'
				addChatList(a)
				// msgList.value.push({
				// 	type: "text",
				// 	text: a.payload.text,
				// 	name: "未知",
				// 	time: a.time
				// })
			}
			if (a.type == "TIMCustomElem") {
				if (a.payload.data == 'tips') {
					// 直播间提示
					// msgList.value.push({
					// 	type: a.payload.data,
					// 	text: a.payload.description,
					// })
					emit('custom', a.payload)
				}
				if (a.payload.data == 'roomHot') emit('custom', a.payload) //更新热度
				if (a.payload.data == 'audio') emit('custom', a.payload) //设置连麦模式
				if (a.payload.data == 'astrolabe') {
					// 发送星盘
					addChatList(a)
					// const text = a.payload.description
					// msgList.value.push({
					// 	type: a.payload.data,
					// 	name: text.split('&&&')[0],
					// 	text: text.split('&&&')[1],
					// 	ids: a.payload.extension
					// })
					// console.log(msgList.value);
				}
				if (a.payload.data == 'img') {
					// 发送图片
					addChatList(a)
					// const text = a.payload.description
					// msgList.value.push({
					// 	type: a.payload.data,
					// 	name: text.split('***')[0],
					// 	text: text.split('***')[1],
					// })
				}
				if (a.payload.data == 'gift' || a.payload.data == 'answer') addChatList({
					...a,
					payload: {
						...a.payload,
						description: JSON.parse(a.payload.description)
					}
				})
				if (a.payload.data == 'live') {
					// 发送礼物
					addChatList(a)
					// const gift = JSON.parse(a.payload.extension)
					// const text = gift.gift
					// console.log(text);
					// msgList.value.push({
					// 	type: 'tips',
					// 	text: `${gift.user}送出了${text.split('***')[0]}`,
					// })
					// emit('custom', a.payload)
				} else {
					emit('custom', a.payload)
				}
			}
		})
		scrollToBottom()
	}
	// 发送礼物
	const pushMsg = (obj) => {
		msgList.value.push(obj)
	}
	const onScroll = e => {
		if (e.detail.scrollHeight - e.detail.scrollTop < 483) {
			scrollType.value = true
		} else {
			scrollType.value = false
		}
	}
	// 发送消息
	const sendMsg = (val) => {
		console.log('发送消息', val);
		const payload = {
			text: val || `${uni.getStorageSync('user').nickname}: ${msg.value}`
		}
		const message = tim.createTextMessage({
			to: params.value.strRoomId,
			conversationType: TencentCloudChat.TYPES.CONV_GROUP,
			payload: payload,
		});
		tim.sendMessage(message);
		getMsg({
			data: [{
				type: "TIMTextElem",
				time: dayjs().unix(),
				payload: payload
			}]
		})
		nextTick(() => {
			msg.value = ""
		})
	}
	// 发送自定义信息 data:类型；description：信息；extension：自定义
	const createCustomMessage = (payload) => {
		console.log('发送自定义信息', payload);
		if (payload.data === 'answer') {
			getMsg({
				data: [{
					from: params.value.userId,
					type: "TIMCustomElem",
					time: dayjs().unix(),
					payload: payload
				}]
			})
		}
		if (payload.data == 'live' && payload.description == 'gift') {
			const gift = JSON.parse(payload.extension)
			pushMsg({
				type: 'tips',
				text: `${gift.user}送出了${gift.gift}号礼物`,
			})
		}
		if (payload.data == 'tips') {
			msgList.value.push({
				type: payload.data,
				text: payload.description,
			})
		}
		const message = tim.createCustomMessage({
			to: params.value.strRoomId,
			conversationType: TencentCloudChat.TYPES.CONV_GROUP,
			payload: payload,
		});
		tim.sendMessage(message);
	}
	// 退出直播间
	const closeChat = () => {
		// if (tim) {
		// 	tim.off(TencentCloudChat.EVENT.MESSAGE_RECEIVED, getMsg)
		// 	tim.destroy()
		// }
		return true
	}
	defineExpose({
		startChat,
		closeChat,
		createCustomMessage,
		getMsg,
		sendMsg
	})
</script>

<style>

</style>